#ifndef __THREADPOOL_HPP__
#define __THREADPOOL_HPP__

#include <queue>
#include <vector>
#include <pthread.h>
#include <functional>
#include "pthread.hpp"
#include "log.hpp"

using namespace mypthread;

template <typename T>
class ThreadPool
{
private:
    bool isEmpty()
    {
        return _q.empty();
    }

    // 构造函数必须是私有
    ThreadPool(int maxnum = 3) : _maxnum(maxnum), isruning(false)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    void handleTask(string name)
    {
        while (true)
        {
            // 1、加锁
            pthread_mutex_lock(&_mutex);

            // 2、获取任务
            // 2.1、获取任务前判断任务队列是否为空和线程是否正常运行
            while (isEmpty() && isruning)
            {
                // 正常运行并且为空，条件变量下等待
                pthread_cond_wait(&_cond, &_mutex);
            }
            if (isEmpty() && !isruning)
            {
                pthread_mutex_unlock(&_mutex);
                break;
            }
            T t;
            t = _q.front();
            _q.pop();
            pthread_mutex_unlock(&_mutex);

            // 3、处理任务
            // 不为空，线程池正常运行
            // 不为空，线程已经暂停 ---- 线程要将任务队列中的任务执行完之后再退出
            t();
        }
    }

    void start() // 启动线程池
    {
        isruning = true;
        for (int i = 0; i < _maxnum; i++)
        {
            string name = "thread-" + to_string(i + 1);
            _tp.emplace_back(bind(&ThreadPool::handleTask, this, placeholders::_1), name);
            LOG(DEBUG, "%s\n", (name + " is starting......").c_str());
            sleep(1);
            //  用bind可以给函数绑定一个参数，传参的时候可以少传一个
            //  bind一般用于类的成员函数之间的调用
        }
        // sleep(3);
    }

    // 拷贝构造和赋值运算符要删除
    ThreadPool(const ThreadPool<T> &tp) = delete;
    ThreadPool<T> &operator=(const ThreadPool<T> &tp) = delete;

public:
    void push(T &in) // 向任务队列中放任务
    {
        pthread_mutex_lock(&_mutex);
        if (isruning)
        {
            _q.emplace(in);
            pthread_cond_signal(&_cond);
        }
        pthread_mutex_unlock(&_mutex);
    }

    void stop() // 终止线程池并等待
    {
        pthread_mutex_lock(&_mutex);
        isruning = false;
        pthread_cond_broadcast(&_cond); // 唤醒所有线程
        pthread_mutex_unlock(&_mutex);

        for (auto thread : _tp) // 等待所有线程
        {
            thread.join();
            LOG(DEBUG, "%s\n", (thread.getName() + " wait is success!").c_str());
        }
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

public:
    // 需要为用户提供一个接口，来获取单例
    // 饿汉方式实现
    static ThreadPool<T> *getInstance()
    {
        if (_ptp == nullptr) // 减少竞争锁的开销，当单例创建成功之后，_ptp不为空就不需要去竞争锁再判断了
        {
            pthread_mutex_lock(&_look); // 创建单例的时候要加锁保护，防止多线程出现问题
            if (_ptp == nullptr)
            {
                _ptp = new ThreadPool<T>();
                _ptp->start();
                LOG(DEBUG, "instance is created successfully!\n");
                pthread_mutex_unlock(&_look);
                return _ptp;
            }
            pthread_mutex_unlock(&_look);
        }
        LOG(DEBUG, "instance is obtained successfully!\n");
        return _ptp;
    }

private:
    queue<T> _q;        // 任务队列
    vector<Thread> _tp; // 存放线程
    int _maxnum;        // 线程池最大线程数

    pthread_mutex_t _mutex; // 保护任务队列的锁
    pthread_cond_t _cond;   // 条件变量
    bool isruning;

    // 单例模式的线程池
    static ThreadPool<T> *_ptp;
    static pthread_mutex_t _look;
};

template <typename T>
ThreadPool<T> *ThreadPool<T>::_ptp = nullptr;

template <typename T>
pthread_mutex_t ThreadPool<T>::_look = PTHREAD_MUTEX_INITIALIZER;

#endif